package com.connect.socket;

import com.dto.cnc.CncDTO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

@Slf4j(topic = "socket服务接口")
public class SocketServie {
    String cncServerHost = CncDTO.getCnc_ip();
    int cncServerPort = Integer.parseInt(CncDTO.getCnc_port());
    String strNew = "";
    StringBuffer sbResult = new StringBuffer();
    @SneakyThrows
    public StringBuffer readBack(/*指令*/String strCode,
                                       String cncServerHost,
                                       int cncServerPort
    ) {
        Socket socket = new Socket();
        //超时则关闭
        if (socket.getSoTimeout() == 0) {
            socket.setSoTimeout(5000);//5s超时时间
        }
        //立即发送TCP请求
        if (!socket.getTcpNoDelay()) {
            socket.setTcpNoDelay(true);
        }
        //立即释放端口并重用
        if (!socket.getReuseAddress()) {
            socket.setReuseAddress(true);
        }
        //检查服务状态，减少因服务器停机导致的过长等待
        if (!socket.getKeepAlive()) {
            socket.setKeepAlive(true);
        }
        //将未发完关闭时的数据包丢弃
        if (socket.getSoLinger() == 0) {
            socket.setSoLinger(true, 0);
        }


        if (CncDTO.getCnc_state().contains("在线")) {


            try {
                //初始化
                SocketAddress address = new InetSocketAddress(cncServerHost, cncServerPort);
                socket.connect(address);
                while (!socket.isConnected()) {
                    log.error("-------socket启动失败-------");
                    socket.close();
                }
//                log.info("-------socket启动成功-------");


                // 读
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
                // 写


                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                bufferedWriter.write(strCode);


//            OutputStream os = socket.getOutputStream();
//            os.write(strCode.hashCode());


                bufferedWriter.write("\n");
                bufferedWriter.flush();

                // 读数据
                if ((strNew = bufferedReader.readLine()) != null) {

                    sbResult = new StringBuffer(strNew); //String转换为StringBuffer

//                    System.out.println(Thread.currentThread().getName() + "获取返回的数据:" + sbResult);

                }
            } catch (Throwable throwable) {
                log.error("错误" + throwable.toString());
            } finally {
                socket.close();
            }
            return sbResult;
         }
        else {
            return sbResult.append("null");
        }
    }
}
